package com.frame.project.service.monitor.operlog.imp;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.persistence.criteria.Predicate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.frame.common.enumutil.RemoveEnum;
import com.frame.common.utils.StringUtils;
import com.frame.common.utils.text.Convert;
import com.frame.project.domain.monitor.operlog.OperLog;
import com.frame.project.repository.monitor.operlog.OperLogRepository;
import com.frame.project.service.monitor.operlog.OperLogService;

/**
 * 
 * @className ：OperLogServiceImpl
 * @describe ：操作日志记录
 */
@Service
public class OperLogServiceImpl implements OperLogService {

	@Autowired
	private OperLogRepository operLogRepository;
	
	/**
     * 分页
     */
	@Override
	public Page<OperLog> findByPage(Integer pageNo, Integer pageSize, OperLog operLog) {
		List<Sort.Order> orders = new ArrayList<>();
		orders.add(new Sort.Order(Sort.Direction.DESC, "operTime"));
		Sort sort = Sort.by(orders);
		Pageable pageable = PageRequest.of(pageNo, pageSize, sort);
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		Page<OperLog> page = operLogRepository.findAll((root, query, cb) ->{
			List<Predicate> list = new ArrayList<>();
			list.add(cb.and(cb.equal(root.get("removeStatus").as(Integer.class), RemoveEnum.NOT_REMOVE.getCode())));
			
			if(StringUtils.isNotBlank(operLog.getTitle())) {
				list.add(cb.and(cb.like(root.get("title").as(String.class), operLog.getTitle())));
			}
			
			if(operLog.getBusinessType() != null) {
				list.add(cb.and(cb.equal(root.get("businessType").as(Integer.class), operLog.getBusinessType())));
			}
			
			if(operLog.getStatus() != null) {
				list.add(cb.and(cb.equal(root.get("status").as(Integer.class), operLog.getStatus())));
			}
			
			if(StringUtils.isNotBlank(operLog.getOperName())) {
				list.add(cb.and(cb.like(root.get("operName").as(String.class), operLog.getOperName())));
			}
			
			Map<String, Object> params = operLog.getParams();
			if(!params.isEmpty()) {
				String beginTime = (String) params.get("beginTime");
				String endTime = (String) params.get("endTime");
				if(StringUtils.isNotBlank(beginTime)) {
					try {
						list.add(cb.and(cb.greaterThanOrEqualTo(root.get("operTime"), sdf.parse(beginTime))));
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(StringUtils.isNotBlank(endTime)) {
					try {
						list.add(cb.and(cb.lessThanOrEqualTo(root.get("operTime"), sdf.parse(endTime))));
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
			Predicate[] p = new Predicate[list.size()];
			return cb.and(list.toArray(p));
		},pageable);
		
		return page;
	}
	
	/**
     * 新增操作日志
     * 
     * @param operLog 操作日志对象
     */
    @Override
    public void insertOperlog(OperLog operLog)
    {
    	OperLog ol = new OperLog();
    	ol.setTitle(operLog.getTitle());
    	ol.setBusinessType(operLog.getBusinessType());
    	ol.setMethod(operLog.getMethod());
    	ol.setRequestMethod(operLog.getRequestMethod());
    	ol.setOperatorType(operLog.getOperatorType());
    	ol.setOperName(operLog.getOperName());
    	ol.setDeptName(operLog.getDeptName());
    	ol.setOperUrl(operLog.getOperUrl());
    	ol.setOperIp(operLog.getOperIp());
    	ol.setOperLocation(operLog.getOperLocation());
    	ol.setOperParam(operLog.getOperParam());
    	ol.setJsonResult(operLog.getJsonResult());
    	ol.setStatus(operLog.getStatus());
    	ol.setErrorMsg(operLog.getErrorMsg());
    	ol.setOperTime(new Date());
    	ol.setRemoveStatus(RemoveEnum.NOT_REMOVE.getCode());
    	
    	operLogRepository.save(ol);
    }
    
    /**
     * 通过操作日志ID查询操作日志
     * 
     * @param operLogId 操作日志ID
     * @return 操作日志对象信息
     */
	@Override
	public OperLog selectOperLogById(Long operLogId) {
		
		Optional<OperLog> Op = operLogRepository.findById(operLogId);
    	if(Op.isPresent()) {
			return Op.get();
		}
        return null;
	}
	
	/**
     * 删除操作日志
     * @param jobId 操作日志ID
     */
	@Override
	public void deleteOperLogById(Long operLogId) {
		
		OperLog operLog = selectOperLogById(operLogId);
    	if(operLog != null) {
    		operLog.setRemoveStatus(RemoveEnum.REMOVE.getCode());
    		operLogRepository.save(operLog);
    	//	operLogRepository.delete(operLog);
    	}
		
	}
	
	/**
     * 批量删除操作日志
     * 
     * @param ids 需要删除的数据
     * @return
     */
	@Override
	public void deleteOperLogByIds(String ids) {

		Long[] strArray = Convert.toLongArray(ids);
        for(Long id : strArray) {
        	deleteOperLogById(id);
        }
        
	}
	
	/**
     * 清空操作日志
     */
	@Override
	public void cleanOperLog() {
		
		List<OperLog> all = operLogRepository.findAll();
		for(OperLog ol : all) {
			ol.setRemoveStatus(RemoveEnum.NOT_REMOVE.getCode());
			operLogRepository.save(ol);
		}
		
	//	operLogRepository.deleteAll();
	}
}
